//
//  ZhanshiPhotoViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/8.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "ZhanshiPhotoViewController.h"
#import "SDPhotoBrowser.h"
#import <UIButton+WebCache.h>
#import "ShowImageMode.h"
#import "LCActionSheet.h"
#import "IWUploadParam.h"
#import <MJExtension.h>
#import "UserInfoUpdateResde.h"
#import <QBImagePickerController/QBImagePickerController.h>
#import "Puser.h"
#import "AppDelegate.h"
#import "ShowPicMode.h"
#import "ShopMenMode.h"
@interface ZhanshiPhotoViewController ()<SDPhotoBrowserDelegate,QBImagePickerControllerDelegate,LCActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic)  UIButton *photobtn1;
@property (weak, nonatomic)  UIButton *photobtn2;
@property (weak, nonatomic)  UIButton *photobtn3;
@property (weak, nonatomic)  UIButton *photobtn4;

@property (nonatomic ,weak) UILabel *numberlable;
@property (nonatomic,strong) NSArray *btnarray;
@property (nonatomic,strong) NSMutableArray *Imagesarray;
@property (nonatomic,strong) UIView *photoView;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) UIImagePickerController *picker;


@end

@implementation ZhanshiPhotoViewController
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(instancetype)init{
    if (self=[super init]) {
        
        
        
        self.view.backgroundColor=bgGarycolor;
        
        UIView *bgview=[[UIView alloc] initWithFrame:CGRectMake(0, 64, XHScreenwidth, 116)];
        bgview.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:bgview];
        UILabel *lable=[[UILabel alloc]init];
        lable.font=[UIFont systemFontOfSize:15];
        lable.textColor=textnormalGary;
        lable.frame=CGRectMake(16, 8, 60, 18);
        NSString *titletext=@"展示照片";
        lable.text=titletext;
        [lable sizeToFit];
        [bgview addSubview:lable];
        self.titlelable=lable;
        
        UILabel *numberlable=[[UILabel alloc]initWithFrame:CGRectMake(0, 8, 0, 18)];
        numberlable.font=[UIFont systemFontOfSize:15];
        numberlable.textColor=textnormalGary;
        numberlable.x=CGRectGetMaxX(lable.frame)+8;
        NSString *numbertext=@"最多4张";
        numberlable.textColor=[UIColor lightGrayColor];
        numberlable.text=numbertext;
        [numberlable sizeToFit];
        [bgview addSubview:numberlable];
        self.numberlable=numberlable;
        
        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(16, 35, XHScreenwidth, 1)];
        line.backgroundColor=BoderColor;
        [bgview addSubview:line];
        
        _photoView=[[UIView alloc]initWithFrame:CGRectMake(0, 36, XHScreenwidth, 80)];
        [bgview addSubview:_photoView];
        
        CGFloat x;
        CGFloat y=8;
        CGFloat width=60;
        CGFloat height=60;
        for (int i=0; i<4; i++) {
            UIButton *btn=[[UIButton alloc]init];
            [btn setImage: [UIImage imageNamed:@"button_photo"] forState:UIControlStateNormal];
            x=XHScreenwidth-8-(8+width)*(i+1);
            btn.frame=CGRectMake(x, y, width, height);
            btn.tag=i;
            btn.hidden=(i!=0);
            
            [btn addTarget:self action:@selector(btnclick:) forControlEvents:UIControlEventTouchUpInside];
            [_photoView addSubview:btn];
        }
        
    }
    return self;
}

-(void)showHasActionSheet:(NSInteger)tag{
    NSArray *titles;
    NSInteger redindex;
    if ([self.user.power integerValue]==8) {
        titles=@[@"查看大图"];
        redindex=-1;
    }else{
        titles=@[@"查看大图",@"重新上传",@"删除"];
        redindex=2;
    }
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:titles redButtonIndex:redindex delegate:self];
    sheet.tag=tag;
    sheet.isTag=YES;
    [sheet show];
}

-(void)showHasActionSheet2:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"查看大图",@"重新上传"] redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    sheet.isTag=YES;
    [sheet show];
}

-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}
-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)showActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"拍照",@"从相册中选取"] redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    [sheet show];
}
-(void)btnclick:(UIButton *)btn{
    if (btn.isSelected) {
        [self showHasActionSheet:btn.tag];
    }else{
        [self showActionSheet:btn.tag];
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        UIButton *btn=self.photoView.subviews[picker.view.tag];
        
        ShowImageMode *imagemode=[[ShowImageMode alloc]init];
        imagemode.needupdate=YES;
        imagemode.image=image;
        imagemode.index=btn.tag;
        if (btn.isSelected) {
            
            [self.Imagesarray replaceObjectAtIndex:btn.tag withObject:imagemode];
        }else{
            [self.Imagesarray addObject:imagemode];
        }
        [self reloadIMG];
        
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        NSMutableArray *marray=[NSMutableArray array];
        for (int i=0;i<assets.count;i++) {
            ALAsset *asset=assets[i];
            UIImage *image=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
            ShowImageMode *mode=[[ShowImageMode alloc]init];
            mode.image=image;
            mode.needupdate=YES;
            mode.index=imagePickerController.view.tag+i;
            [marray addObject:mode];
        }
        
        UIButton *btn=self.photoView.subviews[imagePickerController.view.tag];
        if (btn.isSelected) {
            [self.Imagesarray replaceObjectAtIndex:imagePickerController.view.tag withObject:marray[0]];
            [self reloadIMG];
        }else{
            [self.Imagesarray addObjectsFromArray:marray];
            [self reloadIMG];
        }
    }];
}
-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)showPickerOrCanmra:(UIButton *)button WithIndex:(NSInteger)index{
    
    if (index==0) {
        [self showCarmera:button.tag];
    }else{
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.view.tag=button.tag;
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        
        if (button.isSelected) {
            imagePickerController.maximumNumberOfSelection = 1;
        }else{
            
            imagePickerController.maximumNumberOfSelection = 4-self.Imagesarray.count;
        }
        imagePickerController.showsNumberOfSelectedAssets = YES;
        
        
        [self presentViewController:imagePickerController animated:YES completion:NULL];
    }
}


+(instancetype)viewcontroller{
    ZhanshiPhotoViewController *vc=[[ZhanshiPhotoViewController alloc]init];
    
    return vc;
}

-(NSMutableArray *)Imagesarray{
    if ( _Imagesarray==nil) {
        _Imagesarray=[NSMutableArray array];
    }
    return  _Imagesarray;
}

-(void)setPhotoaray:(NSMutableArray *)photoaray{
    _photoaray=photoaray;
    if (_photoaray==nil) {
        _photoaray=[NSMutableArray array];
    }
    
    [self reloadimage];
}
#pragma actionshseet代理方法
-(void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==actionSheet.btnCount-1) return;
    if (actionSheet.isTag) {
        switch (buttonIndex) {
            case 0:
                [self shoWImage:actionSheet.tag];
                
                break;
            case 1:
                [self showActionSheet:actionSheet.tag];
                break;
            case 2:
            {
                
                [self deleteImage:actionSheet.tag];
                
            }
                break;
            default:
                break;
        }
        
        
    }else{
        UIButton *btn=self.photoView.subviews[actionSheet.tag];
        [self showPickerOrCanmra:btn WithIndex:buttonIndex];
    }
    
}

-(void)deleteImage:(NSInteger)tag{
    if (self.photoaray.count>0) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在删除..";
        
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        if ([self.user.power integerValue]<5) {
            params[@"user_type"]=@"person";
            params[@"user_id"]=self.user.user_id;
            params[@"action"]=@"p_pic_del";
            
            
            
        }else{
            params[@"user_type"]=@"company";
            params[@"action"]=@"c_men_del";
            if (self.user.parent_id&&![self.user.parent_id isEqualToString:@"0"]) {
                params[@"com_id"]=self.user.parent_id;
            }else{
                params[@"com_id"]=self.user.com_id;
            }
        }
        params[@"pic"]=self.photoaray[tag];
        [PostUitls Post:userinfourl parameters:params success:^(id response) {
            NSDictionary *dict=response;
            UserInfoUpdateResde *resde=[UserInfoUpdateResde resdeWithDict:dict];
            if ([resde.state integerValue]==400) {
                hud.mode=MBProgressHUDModeText;
                hud.labelText=@"删除成功";
                if ([self.user.power integerValue]<5) {
                    [self savedeleteState:tag];
                    self.user.show_pics=resde.data;
                
                }else
                {
                    self.user.shop_men_imgs=resde.data;
                    [self setresoultfor:tag];
                }
                [hud hide:YES afterDelay:1];
                [self.Imagesarray removeObjectAtIndex:tag];
                [self reloadIMG];
                
            }else{
                hud.mode=MBProgressHUDModeText;
                hud.labelText=resde.msg;
                [hud hide:YES afterDelay:1];
            }
        } failure:^(NSError *error) {
            hud.mode=MBProgressHUDModeText;
            hud.labelText=@"删除失败";
            [hud hide:YES afterDelay:1];
            
        }];

    }else{
        [self.Imagesarray removeObjectAtIndex:tag];
        [self reloadIMG];
    }
    
}
-(void)setresoultfor:(NSInteger)tag{
    [self.photoaray removeObjectAtIndex:tag];
    if (self.block) {
        if (self.photoaray.count>0) {
            self.block(self.photoaray[0]);
        }else{
            self.block(@"");
        }
        
    }
    AppDelegate *delegate= [[UIApplication sharedApplication]delegate];
    [delegate saveContext];
}
-(void)savedeleteState:(NSInteger)tag{
    [self.photoaray removeObjectAtIndex:tag];
      if (self.photoaray.count>0) {
        self.user.show_pic=@"已上传";
    }
    else{
        self.user.show_pic=@"未上传";
        
    }
    

    AppDelegate *delegate= [[UIApplication sharedApplication]delegate];
    [delegate saveContext];
}
-(void)savestate:(NSString *)data{
    
    if ([self.user.power integerValue]<5) {
          self.user.show_pics=data;
    }else{
        self.user.shop_men_imgs=data;
    }
    AppDelegate *delegate= [[UIApplication sharedApplication]delegate];
    [delegate saveContext];
}
-(void)reloadIMG{
    
    for (int i=0; i<4; i++) {
        UIButton *btn=self.photoView.subviews[i];
        if (i<_Imagesarray.count) {
            ShowImageMode *mode=_Imagesarray[i];
            btn.hidden=NO;
            btn.selected=YES;
            [btn setImage:mode.image forState:UIControlStateSelected];
            
        }else{
            btn.selected=NO;
            btn.hidden=YES;
            if (i==_Imagesarray.count) {
                btn.hidden=NO;
            }
        }
    }
    
}

-(void)reloadimage{
    
    for (int i=0; i<_photoaray.count; i++) {
        UIButton *btn=self.photoView.subviews[i];
        
        NSString *iconurl=[NSString getImageURLstr: _photoaray[i] ];
        
        [btn sd_setImageWithURL:[NSURL URLWithString:iconurl] forState:UIControlStateSelected completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            ShowImageMode *mode=[[ShowImageMode alloc]init];
            mode.image=image;
            mode.index=i;
            [self.Imagesarray addObject:mode];
            if (self.Imagesarray.count==_photoaray.count) {
                [self reloadIMG];
            }
        }];
    }
}

-(void)shoWImage:(NSInteger)index{
    SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
    
    browser.sourceImagesContainerView = self.photoView; // 原图的父控件
    browser.imageCount = self.Imagesarray.count ; // 图片总数
    browser.currentImageIndex = index;
    browser.delegate = self;
    [browser show];
    
}
-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    ShowImageMode *mode=self.Imagesarray[index];
    return mode.image;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([self.user.power integerValue]!=8) {
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(baocunclick)];
    }
    
}
-(void)baocunclick{
    if ([self checkNeedUpload]) {
        [self postImage];
    }
}
-(void)postImage{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在更新";
    
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    NSMutableArray *photoarray=[NSMutableArray array];
    
    
    for (int i=0;i<self.Imagesarray.count;i++) {
        ShowImageMode *mode=self.Imagesarray[i];
        
        if (mode.needupdate) {
            NSData *imagedata=[UIImage compressData:mode.image toMaxFileSize:DefailutPicSize];
            NSString *base64str=[imagedata imageBase64Data:imagedata];
            [photoarray addObject:base64str];
        }else{
            [photoarray addObject:self.photoaray[i]];
        }
        
    }
        NSString *imgp=[NSString DataTOjsonString:photoarray];
        params[@"pic"]=imgp;
    
    if ([self.user.power integerValue]<5) {
        params[@"user_type"]=@"person";
        params[@"user_id"]=self.user.user_id;
        params[@"action"]=@"p_show_pic_change";
    }else{
        params[@"user_type"]=@"company";
        params[@"action"]=@"c_shop_img_change";
        params[@"com_id"]=self.user.com_id;
        
    }
    [PostUitls Post:userinfourl parameters:params success:^(id response) {
        NSLog(@"%@",response);
        NSDictionary *dict=response;
         hud.mode=MBProgressHUDModeText;
        UserInfoUpdateResde *resde=[UserInfoUpdateResde resdeWithDict:dict];
        if ([resde.state intValue]==400) {
            
            [self savestate:resde.data];
        }
        hud.mode=MBProgressHUDModeText;
        hud.labelText=resde.msg;
        [hud hide:YES afterDelay:1];

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        hud.mode=MBProgressHUDModeText;
        hud.labelText=@"网络异常";
        [hud hide:YES afterDelay:1];
    }];
    
    
    
    
}

-(BOOL)checkNeedUpload{
    for (int i=0;i<self.Imagesarray.count;i++) {
        ShowImageMode *mode=self.Imagesarray[i];
        if (mode.needupdate) {
            return YES;
        }else{
            if (i==self.Imagesarray.count-1) {
                MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
                hud.labelText=@"没有需要保存的图片";
                hud.mode = MBProgressHUDModeText;
                hud.margin = 10.f;
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:1];
                
            }
        }
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
